从JSP到Servlet的中文乱码解决方案解析
问题分析
在Java Web开发中,从JSP页面提交表单数据到Servlet时,经常会出现中文乱码问题。主要原因包括:
- JSP页面编码设置不正确
- Servlet未正确处理请求编码
- 服务器默认编码与页面编码不一致
- GET和POST请求处理方式不同
完整解决方案
1. JSP页面设置
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>表单提交示例</title>
</head>
<body>
<form action="yourServlet" method="post">
用户名: <input type="text" name="username"/><br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
2. Servlet处理POST请求
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 设置请求和响应编码
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
// 获取参数
String username = request.getParameter("username");
// 处理业务逻辑...
System.out.println("接收到的用户名: " + username);
// 返回响应
PrintWriter out = response.getWriter();
out.println("处理成功: " + username);
}
3. 处理GET请求乱码
对于GET请求,需要在服务器配置中设置URI编码:
// 在Tomcat的server.xml中配置
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
URIEncoding="UTF-8"/>
或者在Servlet中手动解码:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 获取参数并手动解码
String username = request.getParameter("username");
username = new String(username.getBytes("ISO-8859-1"), "UTF-8");
// 处理业务逻辑...
}
4. 过滤器统一处理编码
创建编码过滤器,统一处理所有请求:
public class EncodingFilter implements Filter {
private String encoding = "UTF-8";
public void init(FilterConfig config) throws ServletException {
String param = config.getInitParameter("encoding");
if(param != null) {
encoding = param;
}
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding(encoding);
response.setCharacterEncoding(encoding);
response.setContentType("text/html;charset=" + encoding);
chain.doFilter(request, response);
}
public void destroy() {}
}
在web.xml中配置过滤器:
<filter>
<filter-name>EncodingFilter</filter-name>
<filter-class>com.yourpackage.EncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>EncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
总结
- 确保JSP页面编码设置为UTF-8
- 在Servlet中设置request和response的编码
- GET请求需要在服务器配置URI编码或手动解码
- 使用过滤器统一处理编码是最佳实践
- 确保数据库连接也使用UTF-8编码(如果涉及数据库操作)
通过以上措施,可以彻底解决JSP到Servlet的中文乱码问题。